import { Nodes, dom } from '@knno/dom';
import { Container } from '../interface';
import { titleBarStyle } from './titleBar.css';
import { Button, button } from '../button/button';
import SVGLeft from '@material-design-icons/svg/filled/chevron_left.svg';
import { DATA } from '../symbol';

export interface TitleBarEventMap {
	leftbtnclick: Event;
	rightbtnclick: Event;
}
export type TitleBarEventKey = keyof TitleBarEventMap;
export type TitleBarEventHandler<T extends TitleBarEventKey, O extends Nodes> = (
	this: O,
	event: TitleBarEventMap[T]
) => void;

export class TitleBar extends Container {
	private [DATA]: {
		left: Button;
		right: Button;
		back: boolean;
	};
	protected get box(): Nodes {
		return new Nodes([]);
	}

	constructor() {
		const btnLeft = button()
			.icon(SVGLeft)
			.on('click', () => {
				if (this.navback()) {
					this.emit(new Event('navback', { bubbles: true }));
				} else {
					this.emit(new Event('leftbtnclick'));
				}
			});
		const btnRight = button().on('click', () => {
			this.emit(new Event('rightbtnclick'));
		});
		super(dom.div(titleBarStyle).append(btnLeft, dom.div().name('title'), btnRight));
		this[DATA] = {
			left: btnLeft,
			right: btnRight,
			back: true,
		};
		this.navback(true);
		this.rightIcon(null);
	}

	navback(): boolean;
	navback(value: boolean): this;
	navback(value?: boolean): boolean | this {
		if (value === undefined) {
			return this[DATA].back;
		}
		this[DATA].back = value;
		return this;
	}

	title(text: string): this;
	title(): string;
	title(text?: string): this | string | undefined {
		const div = this.query('div[name=title]');
		if (typeof text === 'string') {
			div.text(text);
			return this;
		}
		return div.text();
	}

	rightIcon(icon: string | null) {
		if (icon) {
			this[DATA].right.icon(icon);
			this[DATA].right.disabled(false);
		} else {
			this[DATA].right.icon(null);
			this[DATA].right.disabled(true);
		}
		return this;
	}
}

export function titleBar(...className: string[]): TitleBar {
	return new TitleBar().addClass(...className);
}
